package com.codeworker.app.ui.wrapper;

import android.text.Editable;
import android.text.TextWatcher;

/**
 * https://blog.csdn.net/freak_csh/article/details/79277100
 */
public class MyTextWatcher implements TextWatcher {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        String temp = editable.toString();
        if (temp.length() == 0) {
            editable.insert(0, "0");
        }
        int posDot = temp.indexOf(".");
        if (posDot < 0) return;
        // 输入以 “ . ”开头的情况，自动在.前面补0
        if (temp.startsWith(".") && posDot == 0) {
            editable.insert(0, "0");
            return;
        }
        // 输入"08" 等类似情况
        if (temp.startsWith("0") && temp.length() > 1 && posDot > 1) {
            editable.delete(0, 1);
            return;
        }
        // 小数点后面只能有两位小数
        if (temp.length() - posDot - 1 > 2) {
            editable.delete(posDot + 3, posDot + 4);
        }
    }
}
